package com.riant.aop;

import org.apache.commons.codec.binary.Base64;

import java.security.*;
import java.util.Arrays;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestSignature {
    private static final String SHA1WITHRSA = "SHA1withRSA";
    private static final String SHA256WITHRSA = "SHA256withRSA";

    public static void main(String[] args) {
        testAlg();
    }

    /**
     * Java加密类型和算法名称
     */
    public static void testAlg() {
        Provider[] providers = Security.getProviders();
        Arrays.stream(providers).forEach(item -> {
            System.out.println("provider name：" + item.getName());
            for (Provider.Service s : item.getServices()) {
                System.out.println("类型：" + s.getType() + ",算法：" + s.getAlgorithm());
            }
        });
    }

    public static String signatureBySHA1withRSA(PrivateKey privateKey, String message) {
        String result = "";
        try {
            Signature signature = Signature.getInstance(SHA1WITHRSA);
            signature.initSign(privateKey);
            byte[] bytes = message.getBytes();
            signature.update(bytes);
            byte[] sign = signature.sign();
            //base654编码
            result = Base64.encodeBase64String(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean verifyBySHA1withRSA(PublicKey publicKey, String oriMsg, String signMsg) {
        boolean vefifyFlag = false;
        try {
            Signature signature = Signature.getInstance(SHA1WITHRSA);
            signature.initVerify(publicKey);
            byte[] signBytes = Base64.decodeBase64(signMsg);
            byte[] oriBytes = Base64.decodeBase64(oriMsg);
            signature.update(oriBytes);
            vefifyFlag = signature.verify(signBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vefifyFlag;
    }

}
